﻿using Microsoft.VisualStudio.Shell;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using WpfXamlPropertyGridVSIX;

namespace WpfPropertyEditorExtension
{
    /// <summary>
    /// Interaction logic for CustomPropertyToolWindowControl.
    /// </summary>
    public partial class CustomPropertyToolWindowControl : UserControl
    {
        private readonly XamlEditorService _xaml = new XamlEditorService();
        private XElementWrapper _wrapper;
        private DispatcherTimer _timer;
        private int _lastElementStartLine = -1;
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomPropertyToolWindowControl"/> class.
        /// </summary>
        public CustomPropertyToolWindowControl()
        {
            this.InitializeComponent();
            BtnRefresh.Click += (s, e) => { ThreadHelper.ThrowIfNotOnUIThread(); LoadFromCaret(); };
            BtnToggle.Click += (s, e) => ToggleAutoFollow();

            // Setup timer for auto-follow caret
            _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
            _timer.Tick += (s, e) =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                AutoFollowTick();
            };
        }
        private void ToggleAutoFollow()
        {
            if (_timer.IsEnabled)
            {
                _timer.Stop();
                BtnToggle.Content = "自动跟随(关)";
            }
            else
            {
                _timer.Start();
                BtnToggle.Content = "自动跟随(开)";
            }
        }

        private void AutoFollowTick()
        {
            var doc = _xaml.GetActiveXamlDocument();
            if (doc == null) { TxtInfo.Text = "无活动XAML"; return; }

            var caret = _xaml.GetCaretLineColumn(doc, out var fullText);
            if (caret == null) { TxtInfo.Text = "无法获取光标"; return; }

            var el = _xaml.FindElementAtLine(fullText, caret.Value.line);
            if (el == null) { TxtInfo.Text = "未定位到元素"; return; }

            var startLine = _xaml.GetLine(el);
            if (startLine != _lastElementStartLine)
            {
                _lastElementStartLine = startLine;
                _wrapper = new XElementWrapper(el, _xaml);
                WinFormsPropertyGrid.SelectedObject = _wrapper;
                TxtInfo.Text = $"{el.Name.LocalName} @{startLine}";
            }
        }

        private void LoadFromCaret()
        {
            var doc = _xaml.GetActiveXamlDocument();
            if (doc == null) { TxtInfo.Text = "未找到XAML文档"; return; }

            var caret = _xaml.GetCaretLineColumn(doc, out var fullText);
            if (caret == null) { TxtInfo.Text = "无法获取光标"; return; }

            var el = _xaml.FindElementAtLine(fullText, caret.Value.line);
            if (el == null) { TxtInfo.Text = "未定位到元素(将光标放在控件上)"; return; }

            _lastElementStartLine = _xaml.GetLine(el);
            _wrapper = new XElementWrapper(el, _xaml);
            WinFormsPropertyGrid.SelectedObject = _wrapper;
            TxtInfo.Text = $"{el.Name.LocalName} @{_lastElementStartLine}";
        }
        /// <summary>
        /// Handles click on the button by displaying a message box.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event args.</param>
        [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Justification = "Sample code")]
        [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Default event handler naming pattern")]
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(
                string.Format(System.Globalization.CultureInfo.CurrentUICulture, "Invoked '{0}'", this.ToString()),
                "CustomPropertyToolWindow");
        }
    }
}